package com.ocom.aiot.controller;


import com.ocom.aiot.service.AppVerInfoService;
import com.ocom.aiot.service.XfDeviceInfoService;
import com.ocom.common.constant.AiotUrl;
import com.ocom.common.entity.aiot.EntityXfAppVerInfo;
import com.ocom.common.entity.aiot.EntityXfDeviceInfo;
import com.ocom.common.enums.MachEnum;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.RespUtilMach;
import com.ocom.redis.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
public class XfDeviceStateController {

    private final Logger log = LoggerFactory.getLogger(XfDeviceStateController.class);

    @Autowired
    private XfDeviceInfoService xfDeviceInfoService;

    @Autowired
    private AppVerInfoService appVerInfoService;

    @Resource
    private RedisUtil redisUtil;

    // 获取设备状态（getDeviceState）
    @GetMapping(AiotUrl.URL_Aiot_GetDeviceState)
    public RespMachMessage GetDeviceState(String machNo){
        if (machNo.isEmpty()){
            log.error("出厂编号为空： "+machNo);
            return RespUtilMach.error(MachEnum.AUTH_ERROR);
        }
        //1、从AIoT消费设备表xf_device_list查找device_no=machNo的记录
        //如果没有，返回错误（错误码：1）

        EntityXfDeviceInfo entityXfDeviceInfo = xfDeviceInfoService.GetDeviceList(machNo);
        //如果没有，返回错误（错误码：0x0700）
        if ( entityXfDeviceInfo == null){
            log.error("设备数据为空： "+ machNo);
            return RespUtilMach.error(MachEnum.MACH_NOT_MSG);

        }
        //1.修改数据库：
        //xf_device_list . comm_time = 当前系统时间
        try {
            redisUtil.set("HttpAiotMachCommTime:"+machNo,new Date());
//            xfDeviceInfoService.UpdateCommTime(machNo);
        }catch (Exception exception){
            log.error(exception.getMessage());
        }

        //如果xf_device_ list. status!=1，返回错误（错误码：0x0700）
        if (entityXfDeviceInfo.getStatus() != 1){
            log.error("设备状态不为1: "+ entityXfDeviceInfo.getStatus());
            return RespUtilMach.error(MachEnum.DeviceNotActive);
        }



        Map<String,Object> map = new HashMap<>();
        map.put("companyId", entityXfDeviceInfo.getComId());
        map.put("saasNo", entityXfDeviceInfo.getSaasNo());

        return RespUtilMach.success(map);
    }

    /**
     * 获取设备同步信息标志（getDeviceFlag）
     * */
    @GetMapping(AiotUrl.URL_Aiot_GetDeviceFlag)
    public RespMachMessage GetDeviceFlag(String machNo, String versionCode){
        if (machNo.isEmpty()){
            log.error("出厂编号为空： "+machNo);
            return RespUtilMach.error(MachEnum.AUTH_ERROR);
        }
        //1、从AIoT消费设备表xf_device_list找到device_no= machNo的记录
        EntityXfDeviceInfo entityXfDeviceInfo = xfDeviceInfoService.GetDeviceList(machNo);
        if ( entityXfDeviceInfo == null){
            log.error("设备数据为空： "+ machNo);
            return RespUtilMach.error(MachEnum.MACH_NOT_MSG);
        }

        //1.修改数据库：
        //xf_device_list . comm_time = 当前系统时间
        try {
            redisUtil.set("HttpAiotMachCommTime:"+machNo,new Date());
//            xfDeviceInfoService.UpdateCommTime(machNo);
        }catch (Exception exception){
            log.error(exception.getMessage());
        }
        //a1.如果versionCode 不为空且不等于xf_device_list . app_ver，修改数据库：
        //xf_device_list . app_ver = versionCode
        //更新数据
        if (!versionCode.isEmpty() && !versionCode.equals(entityXfDeviceInfo.getAppVer())){
            try {
                xfDeviceInfoService.updateAppVer(entityXfDeviceInfo.getComId(), entityXfDeviceInfo.getDeviceNo(), versionCode);
                entityXfDeviceInfo.setAppVer(versionCode);
            }catch (Exception exception){
                log.error("更新版本失败："+exception.getMessage());
            }
        }


        //2.firmwareUpdate = xf_device_info . app_ver_tab ==”” ? 0 : (app_ver==app_ver_tab ? 0 : 1)
        Integer firmwareUpdate = null;
        String apkUrl = null;
        String appVer = null;
//        log.info("aiot消费设备： 【{}】",entityXfDeviceInfo);
        if (entityXfDeviceInfo.getAppVerTab().isEmpty() || entityXfDeviceInfo.getAppVer().equals(entityXfDeviceInfo.getAppVerTab())){
            firmwareUpdate =0;
        }else {
            //如果firmwareUpdate=1，从总库消费设备app版本信息app_ver_info查app_ver匹配的记录
            //apkUrl = xf_app_ver_info . apk_file_url
            firmwareUpdate = 1;
            try {

                EntityXfAppVerInfo entityXfAppVerInfo = appVerInfoService.selectAppVerInfo(entityXfDeviceInfo.getAppVerTab());
                //升级包查询
                if (entityXfAppVerInfo!=null){
                    apkUrl = entityXfAppVerInfo.getApkFileUrl();
                    appVer = entityXfAppVerInfo.getAppVer();
                }
                if (CommonUtil.isNull(apkUrl)){
                    firmwareUpdate = 0;
                }
            }catch (Exception exception){
                log.error("获取升级版本url失败："+exception);
                firmwareUpdate=0;
            }
        }

        Map<String,Object> map = new HashMap<>();
        map.put("firmwareUpdate",firmwareUpdate);
        map.put("apkUrl",apkUrl);
        map.put("appVer",appVer);
        return RespUtilMach.success(map);
    }


    private Date getCommTime(String machNo,Date commTime){
        Object obj = redisUtil.get("HttpMachCommTime:"+machNo);
        if(obj!=null){
            return (Date) obj;
        }
        if(commTime==null){
            commTime = DateUtils.strToDate("2020-01-01 12:34:56");
        }
        redisUtil.set("HttpMachCommTime:"+machNo,commTime);
        return commTime;
    }

}
